package com.lancoo.examview.exam;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.TextView;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.ivan.easyphotos.constant.CaptureEvent;
import com.lancoo.answer.manager.MediaManager;
import com.lancoo.answer.manager.TaskManager;
import com.lancoo.answer.model.AnswerConstant;
import com.lancoo.answer.model.ConstantBean;
import com.lancoo.answer.model.TaskState;
import com.lancoo.answer.model.bean.Child;
import com.lancoo.answer.model.bean.ImgAnswerCallBackBean;
import com.lancoo.answer.model.bean.Item;
import com.lancoo.answer.model.bean.Ques;
import com.lancoo.answer.model.bean.Type;
import com.lancoo.answer.model.entity.ExamRequireBean;
import com.lancoo.answer.model.entity.IndexBean;
import com.lancoo.answer.model.entity.TaskControlBean;
import com.lancoo.answer.model.entity.callabck.ImgRecognitionCallBack;
import com.lancoo.answer.model.eventBean.CommentsNoteEventBean;
import com.lancoo.answer.model.eventBean.CompleteCurrentAnsPointEventBean;
import com.lancoo.answer.model.eventBean.ImageDownLoadEventBean;
import com.lancoo.answer.model.eventBean.ImageEventBean;
import com.lancoo.answer.model.eventBean.SubmitEventBean;
import com.lancoo.answer.model.eventBean.SwitchQuesEventBean;
import com.lancoo.answer.model.eventBean.VideoEventBean;
import com.lancoo.answer.util.SoftInputUtils;
import com.lancoo.answer.util.paperUtils.PaperDataUtils;
import com.lancoo.examview.R;
import com.lancoo.examview.test.presenter.PaperPresenter;
import com.lancoo.examview.utils.ConvertStremUtils;
import com.lancoo.examview.utils.FontSizeChangeUtils;
import com.rxjava.rxlife.RxLife;
import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.jetbrains.annotations.NotNull;
import java.io.File;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import io.reactivex.Observable;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.Single;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;
import lancoo.com.net.retrofitrxjava.download.FileDownLoadObserver;
import lancoo.com.net.retrofitrxjava.download.HttpDownManager;

public class ExamPaperActivity extends AppCompatActivity {

    private static final String TAG = "PaperActivity";
    private PaperPresenter mPresenter;
    private TaskManager manager;

    private List<Type> typeList;
    private MediaManager mediaManager;
    private TaskControlBean taskControlBean;
    private int startIndex;
    private boolean isShouldShowMark;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Log.e("task","ExamPaperActivity:onCreate");
        setContentView(R.layout.activity_paper);
        mPresenter = new PaperPresenter();
        mediaManager = new MediaManager(this);

        EventBus.getDefault().register(this);

         Observable.create((ObservableOnSubscribe<List<Type>>) emitter -> {
                     SharedPreferences sharedPreferences = getSharedPreferences(AnswerConstant.SP_ANSWER_NAME, Context.MODE_PRIVATE);
                     SharedPreferences.Editor edit = sharedPreferences.edit();
                     edit.putBoolean(AnswerConstant.SP_OPEN_DASH,true);
                     edit.apply();
                     String dataAsset = getIntent().getStringExtra("dataAsset");
                     String originalFundData = ConvertStremUtils.convertStremToString(this, dataAsset);
                     Gson gson = new Gson();
                     typeList = gson.fromJson(originalFundData, new TypeToken<List<Type>>(){}.getType());
                     emitter.onNext(typeList);
                })
                        .subscribeOn(Schedulers.io())
                        .observeOn(AndroidSchedulers.mainThread())
                        .as(RxLife.as(this))
                        .subscribe(this::initView, throwable -> {});

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
        mediaManager.release();
    }

    private void initView(List<Type> typeList) {

        manager = new TaskManager();
        taskControlBean = new TaskControlBean();
        int trainSence = getIntent().getIntExtra("trainSence", 0);
        ExamRequireBean examRequestBean = new ExamRequireBean();
        examRequestBean.setExamName("666考试");
        examRequestBean.setExamTimeLength(120);
        examRequestBean.setTotalQuesCount(50);
        taskControlBean.setExamRequireBean(examRequestBean);
        taskControlBean.setMediaAnswerSaveType(0);
        taskControlBean.setPaperType(0);
        taskControlBean.setCloseMediaAnswer(false);
        //  {"childIndex":8,"itemIndex":0,"quesIndex":0,"typeIndex":6}
//        taskControlBean.setLoadTypIndex(6);
//        taskControlBean.setLoadChildIndex(19);
//        taskControlBean.setLoadItemIndex(0);
//        taskControlBean.setLoadQuesIndex(0);
        taskControlBean.setIsCloseAnswerSheetSubmitBtn(0);
        taskControlBean.setSpokenChildState((owner, parent, layoutType, quesChild) -> {
            Context context = getApplicationContext();

            TextView textView = new TextView(context);
            textView.setText("你可以在这里放口语布局");
            textView.setTextColor(Color.RED);
            textView.setBackgroundColor(Color.YELLOW);
            FrameLayout frameLayout = new FrameLayout(context);
            frameLayout.addView(textView, new ViewGroup.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));
            return frameLayout;
        });
        int onlyShowSize = 1;
        int index = 0;
        startIndex = 0;
        for (Type type:typeList){
            for (Ques ques:type.getQuesList()){
                for(Child child:ques.getChildList()){
                    for (Item item:child.getItemList()){
                        item.setEvalScore(-1f);
                    }
                    child.setEvalScore(-1f);
                }
                index++;
            }
        }
        taskControlBean.setExpired(true);
//        taskControlBean.setTaskState(TaskState.LOOKING);
//        taskControlBean.setOpenZuobiAnswer(true);
        taskControlBean.setMediaAnswerSaveType(0);
        taskControlBean.setTrainSence(1);
        taskControlBean.setTraining(false);
        taskControlBean.setEnableAnwer(1);
        taskControlBean.setPaperType(0);
        manager.loadTaskFragment(getSupportFragmentManager(), taskControlBean, typeList, R.id.framelayout);
//        autoSkipToNextQues();
    }



    /**
     * 提交
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onSubmitEvent(final SubmitEventBean eventBean) {
        Log.e("提交","");
        PaperDataUtils.collectionImgsToRecognition(this, new ImgRecognitionCallBack() {
            @Override
            public void onSuccess() {
                super.onSuccess();
            }
        });

    }
    /**
     * 批注
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onCommentNote(final CommentsNoteEventBean eventBean) {
        Log.e("批注",""+eventBean.getItemIndex());
        PaperDataUtils.collectionImgsToRecognition(this, new ImgRecognitionCallBack() {
            @Override
            public void onSuccess() {
                super.onSuccess();
            }
        });

    }


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_exam_sheet, menu);
        return true;
    }

    @Override
    public boolean onPrepareOptionsMenu(Menu menu) {

        menu.findItem(R.id.menu_mark).setVisible(isShouldShowMark);
        return super.onPrepareOptionsMenu(menu);
    }

    private long time;

    @Override
    public boolean onOptionsItemSelected(@NotNull MenuItem item) {
        if (System.currentTimeMillis() - time < 500) {
            return false;
        }
        time = System.currentTimeMillis();
        if (item.getItemId() == R.id.menu_sheet) {
            if (manager != null) {
                manager.closeAllPaperAudioPlay(getSupportFragmentManager());
                manager.showPaperAnswerSheetDialog(getSupportFragmentManager());
                IndexBean allRealIndex = manager.getAllRealIndex(getSupportFragmentManager());
                int currentPageIndex = allRealIndex.getCurrentPageIndex();
                Log.e("eee", "currentPageIndex" + currentPageIndex);
            }
        } else if(item.getItemId()==R.id.menu_font){
            FontSizeChangeUtils.showFontSizeChangeAlertDialog(this, new FontSizeChangeUtils.FontSizeChangeCallBack() {
                @Override
                public void upDateAllFontSize(int fontIndex, int textSize, int TextZoom) {


                }

                @Override
                public void upDateFontSize(int fontIndex, int textSize, int textZoom) {
                    Log.e("evlog","upDateFontSize:"+fontIndex);
                    if(manager!=null){
                        manager.adjustFontSize(getSupportFragmentManager());
                    }
                }
            });
        }else if(item.getItemId()==R.id.menu_mark){
            if(manager!=null){
                manager.markQuestion(getSupportFragmentManager());
            }
        }
        return super.onOptionsItemSelected(item);
    }


    public static void launch(Context mContext, String dataAsset, TaskState taskState, int trainSence) {
        ConstantBean.setTaskState(taskState);
        Intent mIntent = new Intent(mContext, ExamPaperActivity.class);
        mIntent.putExtra("dataAsset", dataAsset);
        mIntent.putExtra("trainSence", trainSence);
        mContext.startActivity(mIntent);
    }



    /**
     * 试题切换
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onQuesChangeSelect(final SwitchQuesEventBean eventBean) {
        Log.e("试题切换","回调"+new Gson().toJson(eventBean));
        int typeIndex = eventBean.getTypeIndex();
        int quesIndex = eventBean.getQuesIndex();
        int childIndex = eventBean.getChildIndex();
        if(eventBean.getSwitchType()!=0){
            return;
        }
        isShouldShowMark= eventBean.getIsLeaderPage()==0;
        invalidateOptionsMenu();

//        if(typeIndex==3&&quesIndex==0&&childIndex==0){
//            Log.e("试题切换","听力填空");
//            Single.timer(5000, TimeUnit.MILLISECONDS)
//                .observeOn(AndroidSchedulers.mainThread())
//                .as(RxLife.as(this))
//                .subscribe(aLong -> {
//                    Toast.makeText(ExamPaperActivity.this, "自动跳转听力题", Toast.LENGTH_SHORT).show();
//                    manager.skipToAimFragment(getSupportFragmentManager(),3,0,0,0);
//                });
//        }
    }

    /**
     * 下载图片
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onImgDownLoad(ImageDownLoadEventBean eventBean){
        String url=eventBean.getImgServicePath();
        startDownLoadFile(url);
        Log.e("图片处理","回调"+new Gson().toJson(eventBean));
    }

    /**
     * 下载图片
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onImgsUpLoad(ImageEventBean eventBean){
        Log.e("图片上传",new Gson().toJson(eventBean));
    }

    /**
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onCompleteCurrentAnsPointEven(CompleteCurrentAnsPointEventBean eventBean){
        Log.e("completeEvent","需要判断是否全部完成作答");
    }

    /**
     * 拍照识别
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onCapture(final CaptureEvent eventBean) {
        if(manager==null){
            return;
        }
//        Single.timer(20000, TimeUnit.MILLISECONDS)
//                .observeOn(AndroidSchedulers.mainThread())
//                .as(RxLife.as(this))
//                .subscribe(aLong -> {
//                    Toast.makeText(ExamPaperActivity.this, "自动跳转至下一题", Toast.LENGTH_SHORT).show();
//                    manager.skipToAimFragment(getSupportFragmentManager(),1,0,0,0);
//                });

    }


    private void startDownLoadFile(String url){
        String destDir=Environment.getExternalStorageDirectory() + "/Android/data/" + getApplicationInfo().packageName + "/files/record";
        String fileName=System.currentTimeMillis()+"."+url.substring(url.lastIndexOf(".") + 1);
        HttpDownManager.getInstance().downloadFile(url, destDir, fileName, new FileDownLoadObserver<File>() {
            @Override
            public void onDownLoadSuccess(File file) {
                Map<String, String> imgsLocalPathMap = ConstantBean.Companion.getImgsLocalPathMap();
                imgsLocalPathMap.put(url,file.getPath());
            }

            @Override
            public void onDownLoadFail(Throwable throwable) {

            }

            @Override
            public void onProgress(long progress, long total) {

            }
        },this);

    }

    @Override
    protected void onPause() {
        super.onPause();

    }


    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onAudioUpLoadCallBackEvent(final VideoEventBean callBackEventBean) {
        Single.timer(3000, TimeUnit.MILLISECONDS)
                .observeOn(AndroidSchedulers.mainThread())
                .as(RxLife.as(this))
                .subscribe(aLong -> {
                    Toast.makeText(ExamPaperActivity.this, "等待3s后强制关闭语音作答", Toast.LENGTH_SHORT).show();
                    manager.closeAudioAnswerProcess(getSupportFragmentManager());
                });
    }

    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        SoftInputUtils.hideSoftInputOutSite(ev,this);
        return super.dispatchTouchEvent(ev);
    }

    /**
     * 开始作答
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onCaptureEvent(CaptureEvent eventBean) {
        ImgAnswerCallBackBean bean = new ImgAnswerCallBackBean();
        bean.setSubjectIndex(eventBean.getSubjectIndex());
        bean.setTypeIndex(eventBean.getTypeIndex());
        bean.setQuesIndex(eventBean.getQuesIndex());
        bean.setImgUrl("http://123.png");
        bean.setIdentifyContent("测试。。。");
        manager.updateImgAnswerCallBack(getSupportFragmentManager(), bean);
    }

}